<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .body{
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background-color: gray;
            position: absolute;
        }
        .body:first-child{
            background-color: red;
            z-index: 3;
        }
        .food{
            width: 25px;
            height: 25px;
            border-radius: 50%;
            background-color: blue;
            position: absolute;
        }
    </style>
</head>
<body>
    <div class="body"></div>
    <div class="body"></div>
    <div class="body"></div>
    <div class="body"></div>
    <div class="body"></div>

    <script>
        let obody = document.querySelectorAll('.body') ;
        console.log(obody);
        let t
        const maxX = document.documentElement.clientWidth - obody[0].offsetWidth;
        const maxY = document.documentElement.clientHeight - obody[0].offsetHeight;

        addfood() ;
        const ofood = document.querySelector('.food') ;

        document.onkeydown = function(e){
            clearInterval(t)
            e = e || event ;
            const code = e.keycode || e.which ;
            const speed = 25 ;
            let x = obody[0].offsetLeft ;
            let y = obody[0].offsetTop ;
            t = setInterval(function(){
                console.log(x);
                if(code === 37) x-=speed ;
                if(code === 38) y-=speed ;
                if(code === 39) x+=speed ;
                if(code === 40) y+=speed ;
                if(x < 0) x = 0 ;
                if(x > maxX)  x = maxX ;
                if(y < 0) y = 0 ;
                if(y > maxY) y = maxY ;
                obody[0].style.cssText = `left:${x}px;top:${y}px` ;

                for(let i = obody.length-1 ; i > 0 ; i--){
                    obody[i].style.top = obody[i-1].style.top
                    obody[i].style.left = obody[i-1].style.left
                }

                // if(parseInt(Math.abs(obody[0].offsetLeft -ofood.offsetLeft) <= 25 && parseInt(Math.abs(obody[0].offsetTop -ofood.offsetTop) <= 25))){
                //     ofood.remove();
                // }
            } , 100)
        }


        function addfood(){
            const ofood = document.createElement('div') ;
            ofood.classList.add('food') ;
            let x = rand(0 , maxX) * 25;
            let y = rand(0 , maxY) * 25 ;
            ofood.style.cssText = `left:${x}px;top:${y}px` ;
            document.body.appendChild(ofood) ;
        }


        function rand(min , max){
            return parseInt(Math.random()*(max-min)+min) ;
        }
    </script>
</body>
</html>